package com.atguigu.gulimall.cart.interceptor;

import com.atguigu.common.to.MemberRespVo;
import com.atguigu.gulimall.cart.vo.UserInfoTo;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * 在执行目标方法之前，判断用户的登录状态，并且封装传递给controller目标请求
 * @author wfjytd
 * @create 2022-01-06 19:51
 */
@Component
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfoTo userInfoTo = new UserInfoTo();

        HttpSession session = request.getSession();
        MemberRespVo member = (MemberRespVo) session.getAttribute("loginUser");
        if (member != null){
            //用户登录
            userInfoTo.setUserId(member.getId());

        }
        Cookie[] cookies = request.getCookies();
        if (cookies!=null&&cookies.length>0){
            for (Cookie cookie : cookies) {
                //user-key
                String name = cookie.getName();
                if (name.equals("user-key")){
                    userInfoTo.setUserKey(cookie.getValue());
                }
            }
        }
        //如果没有临时用户，要分配
        if (StringUtils.isEmpty(userInfoTo.getUserKey())){
            String uuid = UUID.randomUUID().toString();
            userInfoTo.setUserKey(uuid);
            userInfoTo.setTempUser(true);
        }

        //目标方法执行之前,将信息放入threadLocal，同一个线程共享数据
        threadLocal.set(userInfoTo);
        return true;
    }

    /**
     * 业务执行之后保存cookie
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTo userInfoTo = threadLocal.get();
        if (userInfoTo.isTempUser()){
            //设置临时用户的过期时间
            Cookie cookie = new Cookie("user-key", userInfoTo.getUserKey());
            cookie.setDomain("gulimall.com");
            cookie.setMaxAge(60*60*24*30);
            response.addCookie(cookie);
        }
    }
}
